#include <VLCKit.h> // must be first
#include "vlcplayer.h"

#include <QMacCocoaViewContainer>

class VlcPlayerPrivate
{
public:
    VlcPlayerPrivate():
            pool(0),
            widget(0),
            view(0),
            player(0),
            media(0)
    {
    }

    ~VlcPlayerPrivate()
    {
//        [media release];
        [player release];
        [view release];
        [pool release];
    }


public:
    NSAutoreleasePool* pool;
    QMacCocoaViewContainer* widget;
    VLCVideoView* view;
    VLCMediaPlayer* player;
    VLCMedia* media;
};

// ---------------------------------------------------------------------------------------

VlcPlayer::VlcPlayer(QWidget* parent):
        QObject(parent),
        d(new VlcPlayerPrivate)
{
    // create pool for vlc's autoreleases
    d->pool = [[NSAutoreleasePool alloc] init];

    // create a VLC Video View and bind it to QWidget
    d->view = [[VLCVideoView alloc] init];
    [d->view setAutoresizingMask: NSViewHeightSizable|NSViewWidthSizable];
    d->widget = new QMacCocoaViewContainer(d->view, parent); //.setCocoaView(d->view);

    // create player
    d->player = [[VLCMediaPlayer alloc] initWithVideoView: d->view];
}

VlcPlayer::~VlcPlayer()
{
    delete d;
}

bool VlcPlayer::play(const QString& url)
{
    if (url.isEmpty())
        return false;
    if (d->media)
        stop();

    // setup a new media from uri
//    CFStringRef urlStr = CFStringCreateWithCharacters(
//            0, reinterpret_cast<const UniChar *>(url.unicode()), url.size());
//    CFURLRef urlRef = CFURLCreateWithString(0, urlStr, 0);

    const char* bytes = url.toLatin1();
    NSURL* nsUrl = (NSURL*) CFURLCreateAbsoluteURLWithBytes(
            NULL, (const UInt8 *) bytes, url.length(), kCFStringEncodingUTF8, NULL, TRUE);
    if (!nsUrl)
        nsUrl = (NSURL*) CFURLCreateAbsoluteURLWithBytes(
                NULL, (const UInt8 *) bytes, url.length(), kCFStringEncodingISOLatin1, NULL, TRUE);
    [nsUrl autorelease];
//    NSURL* nsUrl = [NSURL URLWithString:@"http://foo:bar@jjk.kapsi.fi/pub/pw/pisara.mp4"];
    d->media = [VLCMedia mediaWithURL: nsUrl];
    [d->player setMedia: d->media];
//    CFRelease(urlStr);
//    CFRelease(urlRef);

    [d->player setVideoView: d->view];

    // start playing
    return [d->player play];
}

void VlcPlayer::pause()
{
    [d->player pause];
}

void VlcPlayer::stop()
{
    [d->player stop];
    d->media = 0;
}

QWidget* VlcPlayer::widget() const
{
    return d->widget;
}
